﻿Public Class BrowserPage : Inherits Page

	Dim WithEvents Browser As WebBrowser

	ReadOnly Property Address As String
		Get
			If Browser Is Nothing Then Return ""
			If Browser.Url Is Nothing Then Return ""
			Return Browser.Url.ToString
		End Get
	End Property

	Sub Navigate(URL As String)
		Browser = New WebBrowser
		Browser.Dock = DockStyle.Fill
		Controls.Add(Browser)
		Window.Tab.Text = "Bağlanılıyor..."
		Browser.Navigate(URL)
	End Sub

	Dim _Image As Image
	Property Image As Image
		Get
			Return _Image
		End Get
		Set(value As Image)
			_Image = value
			Window.Tab.Invalidate()
			Window.AddressBox.Invalidate()
		End Set
	End Property

	Private Sub Browser_DocumentCompleted(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles Browser.DocumentCompleted
		Window.AddressBox.Invalidate()
		AddHandler Me.Browser.Document.ContextMenuShowing, AddressOf WebContextMenuShowing
		GetIcon()
	End Sub

	Private Sub Browser_DocumentTitleChanged(sender As Object, e As System.EventArgs) Handles Browser.DocumentTitleChanged
		Text = Browser.Document.Title
		Window.Tab.Text = Text
		Window.AddressBox.Invalidate()
	End Sub

	Private Sub GetIcon()
		Dim iconURL = "http://" & Browser.Url.Host & "/favicon.ico"
		Dim request As System.Net.WebRequest = System.Net.HttpWebRequest.Create(iconURL)
		request.BeginGetResponse(AddressOf GetIconDone, request)
	End Sub

	Private Sub Browser_Navigating(sender As Object, e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles Browser.Navigating
		Image = My.Resources.bwmenu
	End Sub

	Private Sub GetIconDone(ByVal result As IAsyncResult)
		Try
			Dim response As System.Net.HttpWebResponse = CType(result.AsyncState, System.Net.WebRequest).GetResponse()
			Dim stream As System.IO.Stream = response.GetResponseStream
			Dim favicon = Image.FromStream(stream)
			If stream.WriteTimeout Then
				Image = favicon
			End If
		Catch ex As Exception
		End Try
	End Sub

	Sub RefreshPage()
		Browser.Refresh()
	End Sub

	Private Sub WebContextMenuShowing(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
		Dim p = Browser.PointToClient(Cursor.Position)
		Window.ShowContextMenu(Me, New MouseEventArgs(Windows.Forms.MouseButtons.Right, 1, p.X, p.Y, 0))
		e.ReturnValue = False
	End Sub
End Class